<template>
  <div>
    <Upload
      :fileList="fileList"
      name="file"
      :showUploadList="false"
      :customRequest="handlePreview"
      @change="handleChange"
    >
      <Button v-if="fileList.length < 1">
        <UploadOutlined />
        上传费用凭证
      </Button>
    </Upload>
    <div v-if="fileList.length >= 1">
      <div v-for="(item, index) in fileList" :key="item.id" class="mb-[5px]">
        <span class="mr-[10px]">{{ item.fileOriginName }}</span>
        <a class="mr-[10px]" @click="setVisible(item)"> 查看 </a>
        <a @click="handleRemove(item, index)"> 清除 </a>
      </div>
    </div>
  </div>
  <!-- <Image
    :width="200"
    :style="{ display: 'none' }"
    :preview="{
      visible: imgVisibleObj.visible,
      onVisibleChange: setVisible,
    }"
    :src="imgVisibleObj.src"
  /> -->
</template>
<script lang="ts" setup>
  import { ref, defineProps, defineOptions, defineEmits, watch, onMounted } from 'vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { message, Upload, Button } from 'ant-design-vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';

  import { uploadApi, delFileApi } from '@/api/escloud/upload';
  // import { v4 as uuidv4 } from 'uuid';

  defineOptions({ name: 'BasicUploadDragger' });

  const props = defineProps({
    params: { type: [Object] },
    fileLists: { type: Array, default: () => [] },
    propUploadApi: { type: Function },
  });
  const emit = defineEmits(['uploadResult']);
  const fileList = ref<any>([]);

  // // 预览图
  // const imgVisibleObj = ref<any>({
  //   visible: false,
  //   src: '',
  // });

  // 预览模块
  const setVisible = (file): void => {
    window.open(file.fileUrl, '_blank');
    // var patterns = /.(jpg|jpeg|png|gif|bmp|JPG|PNG|GIF|BMP|JPEG)$/;
    // if (patterns.test(file.fileOriginName) || !file) {
    //   imgVisibleObj.value = {
    //     visible: !!file,
    //     src: file ? file.fileUrl : '',
    //   };
    // } else {
    //   window.open(file.fileUrl, '_blank');
    // }
  };

  onMounted(() => {
    fileList.value = props.fileLists.map((item: any) => {
      return {
        ...item,
        name: item.fileOriginName || item.name,
        status: 'done',
      };
    });
  });

  watch(
    () => props.fileLists,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fileList.value = props.fileLists.map((item: any) => {
          return {
            ...item,
            name: item.fileOriginName || item.name,
            status: 'done',
          };
        });
      }
    },
    { deep: true }, // 如果 fileLists 是一个深层嵌套的对象数组，可能需要开启深度监听
  );

  const handleChange = (info: UploadChangeParam) => {
    const status = info.file.status;

    if (status === 'done') {
      fileList.value = fileList.value.map((item) => {
        return {
          ...item,
          ...item.response,
        };
      });
    } else if (status === 'error') {
      fileList.value = fileList.value
        .map((item) => {
          if (item.uid === info.file.uid) {
            return null;
          } else {
            return item;
          }
        })
        .filter((ele) => {
          return ele;
        });
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const handlePreview = async (info: UploadRequestOption<any>) => {
    const { onSuccess, onError, file } = info;
    const form = new FormData();
    for (let key in props.params) {
      form.append(key, props.params[key]);
    }
    form.append('file', file);
    const upload = props.propUploadApi ? props.propUploadApi : uploadApi;

    try {
      const res = await upload(form);
      console.log('上传结果', res);
      if (res) {
        emit('uploadResult', res);
        message.success('上传成功');
        fileList.value.push({
          ...res,
        });
        onSuccess &&
          onSuccess({
            ...res,
          });
      } else {
        message.error('上传失败');
        onError && onError(res);
      }
    } catch (error) {
      onError && onError(error);
    }
  };

  const handleRemove = async (file: any, index: number): Promise<void | boolean> => {
    try {
      const res = await delFileApi(file.id);
      res && message.success('删除成功');
      fileList.value.splice(index, 1);
      return !!res;
    } catch (error) {
      message.error(error);
      return false;
    }
  };
</script>
